package cn.tutu.blockchain.minemachine.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.tutu.blockchain.common.Page;
import cn.tutu.blockchain.common.TypeEnum;
import cn.tutu.blockchain.exception.BusinessException;
import cn.tutu.blockchain.minemachine.dao.MinemachineDao;
import cn.tutu.blockchain.minemachine.entity.Minemachine;
import cn.tutu.blockchain.minemachine.service.MinemachineService;

@Service
@Transactional
public class MinemachineServiceImpl implements MinemachineService {

	@Autowired
	private MinemachineDao minemachineDao;

	@Override
	public void create(Minemachine minemachine) {
		Minemachine mc = minemachineDao.findByMachineId(minemachine.getMineMachineId());

		if (null == mc) {
			minemachineDao.insert(minemachine);
		} else {
			if (!StringUtils.isEmpty(mc.getUserId())) {
				throw new BusinessException("该矿机已被绑定!");
			} else {
				minemachine.setId(mc.getId());
				minemachine.setStatus(TypeEnum.STATUS_Y.getCode());
				minemachineDao.update(minemachine);
			}
		}

	}

	@Override
	public void delete(String id) {

		minemachineDao.delete(id);
	}

	@Override
	public PageInfo<Minemachine> getByUserId(String userId, Page page) {
		PageHelper.startPage(page.getPageNum(), page.getPageSize());
		List<Minemachine> list = minemachineDao.findByUser(userId);
		PageInfo<Minemachine> pageInfo = new PageInfo<Minemachine>(list);
		return pageInfo;
	}

	@Override
	public Minemachine getByMachineId(String mineMachineId) {
		return minemachineDao.findByMachineId(mineMachineId);
	}

	@Override
	public int deleteByMacIdAndUserId(String userId, String mineMachineId) {

		return minemachineDao.deleteByMacIdAndUserId(userId, mineMachineId);
	}

	@Override
	public List<Minemachine> getByLastUpdateDate() {
		return minemachineDao.findByLastUpdateDate();
	}

	@Override
	public void updateStatusBatch(List<Minemachine> list) {
		minemachineDao.updateStatusBatch(list);
	}

}
